<template>
	<view class="page-body">
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query v-model="queryForm1.formData" :columns="queryForm1.columns"
			:main-columns="['detection_category', 'client', 'no', 'submitUser', 'remark']" size="mini"
			@search="search"></vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<view>
			<el-row>
				<el-button type="success" size="mini" icon="el-icon-circle-plus-outline" @click="addBtn">添加</el-button>
				<el-button type="success" size="mini" icon="el-icon-circle-plus-outline"
					@click="addBtn('aquatic')">添加(水产)</el-button>
				<el-upload style="display:  inline-block;margin-left: 10px;" size="mini" class="upload-demo"
					ref="upload" action="" :file-list="fileList" :auto-upload="false" :on-change="handleFileChange"
					accept=".xlsx,.xls" :limit="1">
					<el-button slot="trigger" size="mini" type="primary">批量导入</el-button>

				</el-upload>
				<!-- 批量操作 -->
				<el-dropdown v-if="table1.multipleSelection" :split-button="false" trigger="click" @command="batchBtn">
					<el-button type="danger" size="mini" style="margin-left: 20rpx;"
						:disabled="table1.multipleSelection.length === 0">
						批量操作<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item :command="1">批量打印</el-dropdown-item>
						<el-dropdown-item :command="2"
							v-if="$hasPermission(`detection-form-del`)">批量删除</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
			</el-row>
		</view>
		<!-- 自定义按钮区域结束 -->

		<!-- 表格组件开始 -->
		<vk-data-table ref="table1" :rowNo="true" :border="true" :action="table1.action" :columns="table1.columns"
			:query-form-param="queryForm1" size="mini" :right-btns="table1.btn" :selection="true" :pagination="true"
			@update="updateBtn" @delete="deleteBtn" @current-change="currentChange" @selection-change="selectionChange"
			:custom-right-btns="table1.customRightBtns">
			<template v-slot:sample_list="{ row, column, index }">
				<el-popover placement="bottom" width="420" trigger="hover">
					<el-table :data="row.sample_list" stripe size="mini">

						<el-table-column width="150" property="samplename" label="样品名称"></el-table-column>
						<el-table-column width="120" property="yxresult" label="结果"></el-table-column>
						<el-table-column width="150" property="_add_time" label="检测时间">
							<template slot-scope="scope">
								<i class="el-icon-time"></i>
								<span style="margin-left: 10px">{{ $dayjs(row.detect_time).format('YYYY-MM-DD')
								}}</span>
							</template>
						</el-table-column>
					</el-table>
					<view slot="reference"> {{ row.sample_list.length }}</view>
				</el-popover>
			</template>
		</vk-data-table>
		<!-- 表格组件结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog v-model="form1.props.show" :title="form1.props.title" width="1250px" mode="form"
			:close-on-click-modal="false">
			<vk-data-form v-model="form1.data" size="mini" ref="form1" :rules="form1.props.rules"
				:action="form1.props.action" :before-action="form1.props.beforeAction" :form-type="form1.props.formType"
				:columns='form1.props.columns' label-width="120px" @success="form1.props.show = false; refresh();"
				:inline="true" :columnsNumber="3">
				<template v-slot:sample_list="{ form, keyName }">
					<el-button :disabled="!canAdd" type="success" size="mini" icon="el-icon-circle-plus-outline"
						style="margin: 10px 5px;" @click="insertEvent(-1)">添加样品</el-button>
					<vxe-table ref="xTable" keep-source border resizable show-overflow size="small"
						:data="form[keyName]"
						:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }">
						<vxe-table-column fixed="left" type="seq" width="80"></vxe-table-column>
						<vxe-table-column field="sampleno" min-width="200" title="样品编号" align="left" width="200"
							:edit-render="{ name: 'visible', autofocus: '.vxe-input--inner' }">
							<template v-slot:edit="scope">
								<el-input type="text" id="`input_${scope.row.rowNo}`"
									v-model="scope.row.sampleno"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column field="samplename" min-width="250" title="样品名称" align="left" width="250"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:edit="scope">
								<vk-data-input-select size="small" v-model="scope.row.sample_id" :filterable="true"
									:localdata='goodsfilters' placeholder="请选择" :props="{ value: '_id', label: 'name' }"
									width="200px" @change="(val, formData, column, index, option) => {
										scope.row.samplename = formData.name
									}"></vk-data-input-select>
							</template>
						</vxe-table-column>
						<vxe-table-column field="result" min-width="250" title="检测结论" align="left" width="250"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:edit="scope">
								<vk-data-input-select size="small" v-model="scope.row.result_value"
									:localdata='[{ value: 1, label: "合格" }, { value: 0, label: "不合格" }]'
									placeholder="请选择" width="230px" @change="(val, formData, column, index, option) => {

										if (scope.row.result_value == 1) {
											scope.row.result = `经检测${form1.data.detection_standard_name}未超出相关要求`;
											scope.row.yxresult = '阴性';
										}
										else {
											scope.row.result = `经检测${form1.data.detection_standard_name}已超出相关要求`
											scope.row.yxresult = '阳性';
										}
									}"></vk-data-input-select>
							</template></vxe-table-column>
						<vxe-table-column field="remark" min-width="200" title="备注" align="left" width="200"
							:edit-render="{ name: 'visible', }">
							<template v-slot:edit="scope">
								<vxe-input v-model="scope.row.remark" type="text"></vxe-input>
							</template></vxe-table-column>
						<vxe-column title="操作" width="150">
							<template #default="{ row }">
								<template>
									<el-button type="success" v-if="row.isSave == undefined || row.isSave != 1"
										@click="marksur(row)">确定</el-button>
									<el-button type="danger" @click="removeEvent(row)">删除</el-button>
								</template>
							</template>
						</vxe-column>

					</vxe-table>
				</template>
			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->

		<vk-data-dialog v-model="aquatic_form.props.show" :title="aquatic_form.props.title" width="1350px" mode="form"
			:close-on-click-modal="false">
			<vk-data-form v-model="aquatic_form.data" size="mini" ref="form1" :rules="aquatic_form.props.rules"
				:action="aquatic_form.props.action" :before-action="aquatic_form.props.beforeAction"
				:form-type="aquatic_form.props.formType" :columns="aquatic_form.props.columns" label-width="120px"
				@success="
					aquatic_form.props.show = false;
				refresh();
				" :inline="true" :columnsNumber="2">
				<template v-slot:sample_list="{ form, keyName }">
					<el-button type="success" size="mini" :disabled="!$fn.isNotNull(aquatic_form.data.samplename)"
						icon="el-icon-circle-plus-outline" style="margin: 10px 5px"
						@click="insertAquaticEvent(-1)">添加检测项目</el-button>
					<!-- <el-button type="warning" size="mini" icon="el-icon-check" style="margin: 10px 5px"
                        @click="batchConfirmAllSamples('aquatic')">一键确认所有样品</el-button> -->
					<vxe-table ref="xAQTable" keep-source border resizable show-overflow size="small"
						:data="form[keyName]"
						:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }">
						<vxe-table-column fixed="left" type="seq" width="80"></vxe-table-column>
						<vxe-table-column field="detection_category" width="200" align="left"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:header>
								<span>检测项目</span>
								<el-button type="text" size="mini" icon="el-icon-plus"
									@click="batchSetAquaticDetectionCategory" style="margin-left: 5px; color: #409EFF;">
									批量
								</el-button>
							</template>
							<template v-slot:edit="scope">
								<el-select size="small" v-model="scope.row.detection_category" filterable
									placeholder="请选择" style="width: 180px" @change="(val) => {
										const option = aquatic_form.data.detection_category_list.find(item => item._id === val);
										handel_AQ_detection_categoryChange(val, option, scope.row);
									}">
									<el-option v-for="item in aquatic_form.data.detection_category_list" :key="item._id"
										:label="item.name" :value="item._id">
										<div style="display: flex; justify-content: space-between; width: 100%">
											<span>{{ item.name }}</span>
											<span style="color: #909399; font-size: 12px">{{ item.detection_include ||
												'' }}</span>
										</div>
									</el-option>
								</el-select>
							</template>
						</vxe-table-column>
						<vxe-table-column field="detection_standard" title="检测方法" align="left" width="180"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:edit="scope">
								<el-input v-model="scope.row.detection_standard" type="text"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column field="standardRequir" min-width="200" title="标准要求" align="left" width="150"
							:edit-render="{ name: 'visible' }">
							<template v-slot:edit="scope">
								<el-input v-model="scope.row.standardRequir" type="text"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column field="unit" min-width="200" title="计量单位" align="left" width="150"
							:edit-render="{ name: 'visible' }">
							<template v-slot:edit="scope">
								<el-input v-model="scope.row.unit" type="text" placeholder="μg/kg"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column field="result" title="检测结果" align="left" width="200"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:edit="scope">
								<div style="display: flex; align-items: center;">
									<vk-data-input-select size="small" v-model="scope.row.result_value" :localdata="[
										{ value: 1, label: '合格' },
										{ value: 0, label: '不合格' }
									]" placeholder="请选择" width="90px" @change="
										(val, formData, column, index, option) => {
											if (scope.row.result_value == 1) {
												scope.row.result = `阴性`;
												scope.row.yxresult = '合格';
											} else {
												scope.row.result = `阳性`;
												scope.row.yxresult = `不合格`;
											}
										}
									"></vk-data-input-select>
									<el-input v-model="scope.row.result" type="text" size="small"
										style="margin-left: 5px; width: 100px;" placeholder="可继续编辑"></el-input>
								</div>
							</template>
						</vxe-table-column>
						<vxe-table-column field="remark" title="备注" align="left" width="150"
							:edit-render="{ name: 'visible', autoselect: true }">
							<template v-slot:edit="scope">
								<el-input type="text" placeholder="请输入备注" v-model="scope.row.remark" maxlength="8"
									show-word-limit></el-input>
								<!-- <el-input v-model="scope.row.remark" type="text"></el-input> -->
							</template>
						</vxe-table-column>
						<vxe-column title="操作" width="150">
							<template #default="{ row }">
								<template>
									<el-button type="success" v-if="row.isSave == undefined || row.isSave != 1"
										@click="mark_aquatic_sur(row)">确定</el-button>
									<el-button type="danger" @click="removeAquaticEvent(row)">删除</el-button>
								</template>
							</template>
						</vxe-column>
					</vxe-table>
				</template>
			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog v-model="form2.props.show" :title="form2.props.title" width="1150px" mode="form"
			:close-on-click-modal="false">
			<vk-data-form v-model="form2.data" size="mini" ref="form2" :rules="form2.props.rules"
				:action="form2.props.action" :before-action="form2.props.beforeAction" :form-type="form2.props.formType"
				:columns='form2.props.columns' label-width="120px" @success="form2.props.show = false; refresh();"
				:inline="true" :columnsNumber="3">

			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->
		<print v-model="print" />
		<aquaticPrint v-model="print_aquatic" />
		<!-- 页面内容结束 -->
	</view>
</template>

<script>
import XLSX from 'xlsx'
import print from './printbyPrintjs'
import aquaticPrint from './aquaticPrint';
import pinyin from 'js-pinyin';
import { remove, concat, find, includes, orderBy, uniqBy } from 'lodash'

var that;													// 当前页面对象
var vk = uni.vk;									// vk实例
var originalForms = {};						// 表单初始化数据

export default {
	components: {
		print,
		aquaticPrint
	},
	data() {
		// 页面数据变量
		return {
			// 页面是否请求中或加载中
			loading: false,
			fileList: [],
			detection_category_list: {},
			detection_categorys: [],//检测项目
			goods: [],//商品
			clients: [],//委托
			print: {
				show: false,
				printData: []
			}, print_aquatic: {
				show: false,
				printData: []
			},

			// init请求返回的数据
			data: {

			},
			// 表格相关开始 -----------------------------------------------------------
			table1: {
				// 表格数据请求地址
				action: "admin/testing/detection-form/sys/getList",
				// 表格字段显示规则
				columns: [
					// { key:"_id", title:"id", type:"text", width:220 },

					{ key: "no", title: "检测编号", type: "text", width: 200, sortable: "custom" },
					{ key: "client_name", title: "委托单位/人", type: "text", width: 200, sortable: "custom" },
					{
						key: 'type',
						title: '类别',
						type: 'html',
						width: 100,
						sortable: 'custom',
						formatter: (val, row, column, index) => {
							let str = ``;
							if (that.$fn.isNotNull(val)) {
								if (val == 'aquatic') {
									str = `<text style="background:#409EFF;padding:10px;color:#fff">水产</text>`;
								} else if (val == 'enzyme') {
									str = `<text style="background:#E6A23C;padding:10px;color:#fff">酶抑制</text>`;
								} else {
									str = `<text>常规</text>`;
								}
							} else {
								str = `<text>常规</text>`;
							}
							return str;
						}
					},
					{ key: "detection_type", title: "检测类别", type: "text", width: 100, sortable: "custom" },
					{ key: "submitUser", title: "抽/送样者", type: "text", width: 150, sortable: "custom" },
					{ key: "detection_category", title: "检测项目", type: "text", width: 150, sortable: "custom", formatter: this.detection_categorys_fomattr },
					{ key: "detection_standard", title: "检测标准", type: "text", width: 150, sortable: "custom" },
					{ key: "sample_list", title: "样品个数", type: "text", width: 80, sortable: "custom" },
					{ key: "detection_user", title: "检测人", type: "text", width: 100, sortable: "custom" },
					{ key: "printcount", title: "打印次数", type: "text", width: 100, sortable: "custom" },
					{ key: "detect_time", title: "填单时间", type: "time", valueFormat: "yyyy年MM月dd日", width: 150, sortable: "custom" },
					{ key: "sample_save_info", title: "样品存放信息", type: "text", width: 200, sortable: "custom" },
					{ key: "sample_keeptime", title: "留样时间", type: "time", valueFormat: "yyyy年MM月dd日", width: 200, sortable: "custom" },
					{ key: "sample_troptime", title: "弃样时间", type: "time", valueFormat: "yyyy年MM月dd日", sortable: "custom" },
					// { key:"_add_time", title:"添加时间", type:"time", width:160, sortable:"custom"  },
					// { key:"_add_time", title:"距离现在", type:"dateDiff", width:120 },
				],
				// 多选框选中的值
				multipleSelection: [],
				// 当前高亮的记录
				selectItem: "",
				btn: [],
				customRightBtns: [
					{
						title: '打印', type: 'success', icon: 'el-icon-plus',
						show: (item) => {
							return that.isDateBeforeOrEqualToToday(item.detect_time)
						},
						onClick: (item) => {
							if (that.$fn.isNotNull(item.type) && item.type == 'aquatic') {
								that.print_aquatic.printData = [];
								that.print_aquatic.show = true;
								that.print_aquatic.printData.push(vk.pubfn.deepClone(item));
							} else if (that.$fn.isNotNull(item.type) && item.type == 'enzyme') {
								that.print_enzyme.printData = [];
								that.print_enzyme.show = true;
								that.print_enzyme.printData.push(vk.pubfn.deepClone(item));
							} else {
								that.print.printData = [];
								that.print.show = true;
								that.print.printData.push(vk.pubfn.deepClone(item));
							}
						}
					},
					{
						title: '填单时间',
						show: (item) => {

							return this.$hasRole("admin") || this.$hasPermission("detection-form-edittime")
						},
						onClick: (item) => {
							that.form2.props.action = 'admin/testing/detection-form/sys/update';
							that.form2.props.formType = 'update';
							that.form2.props.title = '填单时间管理';
							that.form2.props.show = true;
							that.form2.data = item;


						}
					}
				],
			},
			// 表格相关结束 -----------------------------------------------------------
			// 表单相关开始 -----------------------------------------------------------
			// 查询表单请求数据
			queryForm1: {
				// 查询表单数据源，可在此设置默认值
				formData: {

				},
				// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
				columns: [
					// { key: "client", title: "委托单位/人", type: "text", width: 160, mode: "%%" },
					{
						key: "detection_category", title: "检测项目", type: "remote-select", placeholder: "请选择分类",
						action: "admin/base/detection_category/sys/getList",
						props: { list: "rows", value: "_id", label: "name" },
						showAll: true,
						actionData: {
							pageSize: 1000
						}, width: 150
					},
					{
						key: "client", title: "委托单位/人", type: "select", placeholder: "请选择分类",
						filterable: true,
						data: [],
						props: { list: "rows", value: "_id", label: "name" },
						width: 150
					},

					{ key: "no", title: "编号", type: "text", width: 160, mode: "%%" },
					{ key: "submitUser", title: "抽/送样者", type: "text", width: 160, mode: "%%" },
					{
						key: "remark", title: "备注", type: "text", width: 160,
						mode: "%%", fieldName: "sample_list.remark", lastWhereJson: true
					},
					{ key: "detect_time", title: "填单时间", type: "datetimerange", width: 380, mode: "[]" },
				]
			},
			form1: {
				// 表单请求数据，此处可以设置默认值
				data: {
					detection_user: vk.getVuex('$user.userInfo').nickname,
					sample_list: []
				},
				// 表单属性
				props: {
					// 表单请求地址
					action: "",
							beforeAction: (formData) => {
						const $table = this.$refs.xTable
						const { insertRecords, removeRecords, updateRecords } = $table.getRecordset()
						if (that.$fn.isNull(formData.sample_list)) {
							formData.sample_list = []
						}
						if (that.$fn.isNull(formData.detect_time)) {
							// 创建一个新的Date对象，表示今天的日期
							const today = new Date();

							// 为了得到下一天，我们需要在天数上加1
							// 可以通过设置Date对象的日期属性来实现，今天的日期加上1天
							today.setDate(today.getDate() + 1);
							formData.detect_time = today.getTime();
						}
						if (formData.sample_list.length > 0)
							formData.sample_list = concat(formData.sample_list, insertRecords);
						else
							formData.sample_list = insertRecords;
						removeRecords.forEach(element => {
							let _del = find(formData.sample_list, x => {
								if (that.$fn.isNull(x.rowNo)) {
									return x._X_ROW_KEY == element._X_ROW_KEY
								} else
									return x.rowNo == element.rowNo
							})
							that.$set(_del, 'isdel', true)
						})
						if (that.$fn.isNull(formData.sample_list)) {
							vk.alert(`至少包含一条样品检测数据`)
							return false;
						}

						try {
							let i = 1;
							formData.sample_list.forEach(element => {
								if (that.$fn.isNull(element.isSave) || element.isSave == 0) {

									throw new Error(`第${i}行数据未确认`)
								}
								i++;
							});
						} catch (e) {
							vk.alert(e.message)
							return false;
						}
						// 可在此处修改 formData 后返回 formData，若在此处return false，则表单不触发提交请求。


						return formData;
					},
					// 表单字段显示规则
					columns: [

						{
							key: "client", title: "委托单位/人", type: "remote-select", placeholder: "请选择委托单位/人",
							filterable: true,
							action: "admin/base/client/sys/getalllist",
							props: { list: "rows", value: "_id", label: "name" },

							showAll: true,
							actionData: {
								pageSize: -1
							},
							watch: ({ value, formData, column, index, option, $set }) => {
								$set('submitUser', option.name)
								$set('client_name', option.name)
							},
							width: 200
						},
						{
							key: "detection_type", title: "检测类别", type: "select", filterable: true, clearable: true,
							data: [
								{ value: "送检", label: "送检" },
								{ value: "抽检", label: "抽检" }
							],
							width: 200
						},

						{ key: "submitUser", title: "抽/送样者", type: "text", width: 200, sortable: "custom" },
						{
							key: "detection_category", title: "检测项目", type: "select", filterable: true, clearable: true, placeholder: "请选择检测项目",
							data: [],
							props: { value: "_id", label: "name" },

							watch: ({ value, formData, column, index, option, $set }) => {

								let _result = that.detection_categorys.find(x => x._id == value)
								$set("detection_standard_name", that.$fn.isNotNull(_result) ? `${_result.name}` : '');
								$set("detection_standard", that.$fn.isNotNull(_result) ? `${_result.standard}` : '');
							}
						},

						{ key: "detection_standard", title: "检测标准", type: "text", width: 200, sortable: "custom" },
						{ key: "sample_save_info", title: "样品存放信息", type: "text", width: 200, sortable: "custom" },
						{ key: "sample_keeptime", title: "留样时间", type: "date", dateType: "datetime", width: 200, sortable: "custom" },
						{ key: "sample_troptime", title: "弃样时间", type: "date", dateType: "datetime", sortable: "custom" },
						{ key: "detection_user", title: "检测人", type: "text", width: 200, sortable: "custom", disabled: true, },
						{ key: "sample_list", title: "", type: "text" },
					],
					// 表单验证规则
					rules: {
						client: [
							// 必填
							{ required: true, message: "委托单位/人不能为空", trigger: 'change' }
						],
						detection_type: [
							// 必填
							{ required: true, message: "检测类别", trigger: 'change' }
						],
						submitUser: [
							// 必填
							{ required: true, message: "抽/送样者", trigger: 'change' }
						],
						detection_category: [
							// 必填
							{ required: true, message: "检测项目", trigger: 'change' }
						],
						detection_standard: [
							// 必填
							{ required: true, message: "检测标准", trigger: 'change' }
						],
						detection_user: [
							// 必填
							{ required: true, message: "检测人", trigger: 'change' }
						],
					},
					// add 代表添加 update 代表修改
					formType: "",
					// 是否显示表单的弹窗
					show: false
				}
			},
			form2: {
				// 表单请求数据，此处可以设置默认值
				data: {

				},
				// 表单属性
				props: {
					// 表单请求地址
					action: "",

					// 表单字段显示规则
					columns: [

						{
							key: "client_name", title: "委托单位/人", type: "text", placeholder: "请选择委托单位/人",
							disabled: true,
							props: { list: "rows", value: "_id", label: "name" },
							data: [],

							width: 200
						},
						{
							key: "detection_type", title: "检测类别", type: "select", filterable: true, clearable: true,
							data: [
								{ value: "送检", label: "送检" },
								{ value: "抽检", label: "抽检" }
							],
							disabled: true,
							width: 200
						},

						{ key: "submitUser", title: "抽/送样者", type: "text", width: 200, sortable: "custom", disabled: true, },
						{
							key: "detection_standard_name", title: "检测项目", type: "text", filterable: true, clearable: true, placeholder: "请选择检测项目",
							data: [],
							props: { value: "_id", label: "name" },
							disabled: true,

						},
						{ key: "detection_standard", title: "检测标准", disabled: true, type: "text", width: 200, sortable: "custom" },
						{ key: "detection_user", title: "检测人", disabled: true, type: "text", width: 200, sortable: "custom" },
						{ key: "detect_time", title: "填单时间", type: "date", dateType: "date", width: 200, sortable: "custom" },
					],
					// 表单验证规则
					rules: {
						client: [
							// 必填
							{ required: true, message: "委托单位/人不能为空", trigger: 'change' }
						],
						detection_type: [
							// 必填
							{ required: true, message: "检测类别", trigger: 'change' }
						],
						submitUser: [
							// 必填
							{ required: true, message: "抽/送样者", trigger: 'change' }
						],
						detection_category: [
							// 必填
							{ required: true, message: "检测项目", trigger: 'change' }
						],
						detection_standard: [
							// 必填
							{ required: true, message: "检测标准", trigger: 'change' }
						],
						detection_user: [
							// 必填
							{ required: true, message: "检测人", trigger: 'change' }
						],
					},
					// add 代表添加 update 代表修改
					formType: "",
					// 是否显示表单的弹窗
					show: false
				}
			},
			aquatic_form: {
				// 表单请求数据，此处可以设置默认值
				data: {
					detection_user: vk.getVuex('$user.userInfo').nickname,
					detection_type: '委托检测',
					sample_status: '袋装 鲜样',
					detection_category_list: []
				},
				// 表单属性
				props: {
					// 表单请求地址
					action: '',
					      beforeAction: _formData => {
                        const $table = this.$refs.xAQTable;
                        let formData = JSON.parse(JSON.stringify(_formData));
                        const { insertRecords, removeRecords, updateRecords } = $table.getRecordset();
                        if (that.$fn.isNull(formData.sample_list)) {
                            formData.sample_list = [];
                        }

                        if (that.$fn.isNull(formData.detect_time)) {
                            formData.detect_time = new Date().getTime();
                        }
                        if (formData.sample_list.length > 0) {
                            formData.sample_list = uniqBy(concat(formData.sample_list, insertRecords, updateRecords), `_X_ROW_KEY`);
                        } else formData.sample_list = insertRecords;
                        removeRecords.forEach(element => {
                            let _del = find(formData.sample_list, x => {
                                if (that.$fn.isNull(x.rowNo)) {
                                    return x._X_ROW_KEY == element._X_ROW_KEY;
                                } else return x.rowNo == element.rowNo;
                            });
                            that.$set(_del, 'isdel', true);
                        });

                        try {
                            let i = 1;
                            formData.sample_list.forEach(element => {
                                if (that.$fn.isNull(element.isSave) || element.isSave == 0) {
                                    throw new Error(`第${i}行数据未确认`);
                                }
                                i++;
                            });
                        } catch (e) {
                            vk.alert(e.message);
                            return false;
                        }
                        formData.sample_list.map(x => {
                            that.$set(x, 'sampleno', formData.sampleno);
                            that.$set(x, 'samplename', formData.samplename);
                            that.$set(x, 'sample_id', formData.sample_id);
                        });
                        if (that.$fn.isNull(formData.sample_list.filter(x => that.$fn.isNull(x.isdel) || !x.isdel))) {
                            vk.alert(`至少包含一条样品检测数据`);
                            return false;
                        }

                        console.log(formData);

                        return formData;
                    },
					// 表单字段显示规则
					columns: [
						{
							key: 'client',
							title: '委托单位/人',
							type: 'remote-select',
							placeholder: '请选择委托单位/人',
							filterable: true,
							action: 'admin/base/client/sys/getalllist',
							props: { list: 'rows', value: '_id', label: 'name' },

							showAll: true,
							actionData: {
								pageSize: -1
							},
							watch: ({ value, formData, column, index, option, $set }) => {
								$set('submitUser', option.name);
								$set('client_name', option.name);
								$set('address', option.address);
								if (that.$fn.isNull(option.addressps)) {
									$set('addressps', option.address);
								} else
									$set('addressps', option.addressps);

							},
							width: 300
						},
						{
							key: 'detection_type',
							title: '检测类别',
							type: 'select',
							filterable: true,
							clearable: true,
							data: [
								{ value: '委托检测', label: '委托检测' },
								{ value: '抽检', label: '抽检' },
								{ value: '驻点抽检', label: '驻点抽检' }
							],
							width: 300
						},
						{ key: 'sampleno', title: '样品编号', type: 'text', width: 300, sortable: 'custom' },
						{
							key: 'samplename',
							title: '样品名称',
							type: 'select',
							filterable: true,
							props: { list: 'rows', value: '_id', label: 'name' },
							placeholder: '请选择样品',

							watch: ({ value, formData, column, index, option, $set }) => {
								console.log(option, 'option');

								let _arry = this.detection_categorys.filter(x => option.detection_category.includes(x._id));
								$set('detection_category_list', _arry);
								$set('sample_id', option._id);
								$set('samplename', option.name);

								// 自动生成样品编号：样品名称拼音首字母 + 001
								let _bh = pinyin.getCamelChars(option.name) + '001';
								$set('sampleno', _bh);
							},
							data: [],
							width: 300
						},
						{ key: 'address', title: '委托单位地址', type: 'text', width: 300, sortable: 'custom' },
						{ key: 'submitUser', title: '抽/送样者', type: 'text', width: 300, sortable: 'custom' },
						{ key: 'addressps', title: '抽/送样者地址', type: 'text', width: 300, sortable: 'custom' },
						{ key: 'sample_status', title: '样品状态', type: 'text', width: 300, sortable: 'custom', defaultValue: '袋装 鲜样' },
						//   { key: 'contact', title: '联系人', type: 'text', width: 300, sortable: 'custom' },
						//   { key: 'contact_number', title: '联系方式', type: 'text', width: 300, sortable: 'custom' },
						// { key: "sale_for", title: "销售流向", type: "text", width: 300, sortable: "custom" },


						{ key: 'detection_user', title: '检测人', type: 'text', width: 300, sortable: 'custom', disabled: true },
						{ key: 'remark', title: '备注', type: 'text', width: 800, sortable: 'custom', oneLine: true },
						{ key: 'sample_list', title: '', type: 'text', width: 800, oneLine: true }
					],
					// 表单验证规则
					rules: {
						client: [
							// 必填
							{ required: true, message: '委托单位/人不能为空', trigger: 'change' }
						],
						detection_type: [
							// 必填
							{ required: true, message: '检测类别能为空', trigger: 'change' }
						],
						submitUser: [
							// 必填
							{ required: true, message: '抽/送样者能为空', trigger: 'change' }
						],

						detection_user: [
							// 必填
							{ required: true, message: '检测人能为空', trigger: 'change' }
						],
						sampleno: [
							// 必填
							{ required: true, message: '样品编号能为空', trigger: 'change' }
						],
						samplename: [
							// 必填
							{ required: true, message: '样品名称能为空', trigger: 'change' }
						]
					},
					// add 代表添加 update 代表修改
					formType: '',
					// 是否显示表单的弹窗
					show: false
				}
			},
			// 其他弹窗表单
			formDatas: {},
			// 表单相关结束 -----------------------------------------------------------
		};
	},
	watch: {
		clients(newval, oldval) {

			let _obj = that.form1.props.columns.find(x => x.key == 'client')
			that.$set(_obj, 'data', newval)
			let _obj1 = that.queryForm1.columns.find(x => x.key == 'client')
			that.$set(_obj1, 'data', newval)
		},
		detection_categorys(newval, oldval) {

			let _obj = that.form1.props.columns.find(x => x.key == 'detection_category')
			that.$set(_obj, 'data', newval)
		},
		goods(newval, oldval) {
			let _obj = that.aquatic_form.props.columns.find(x => x.key == 'samplename');
			that.$set(_obj, 'data', newval);
		},
		'form1.data.sample_list': {
			handler(newVal, oldVal) {

				if (that.$fn.isNotNull(newVal) && newVal.length > 0) {
					that.form1.props.columns.forEach(element => {
						// console.log(element)

						that.$set(element, 'disabled', true)
					});
				} else {
					console.log(newVal)
					that.form1.props.columns.forEach(element => {
						// console.log(element)
						if (element.key != 'detection_user')
							that.$set(element, 'disabled', false)
					});
				}
			},
		}
	},
	// 计算属性
	computed: {
		canAdd: function () {
			// 依赖 a 和 b，当 a 或 b 的值变化时，这个计算属性会重新计算
			return this.$fn.isNotNull(this.form1.data.client)
				&& this.$fn.isNotNull(this.form1.data.detection_type)
				&& this.$fn.isNotNull(this.form1.data.submitUser)
				&& this.$fn.isNotNull(this.form1.data.detection_category)
				&& this.$fn.isNotNull(this.form1.data.detection_standard)

		},
		goodsfilters: function () {

			return this.goods.filter(x => includes(x.detection_category, this.form1.data.detection_category))
		}
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options = {}) {
		that = this;
		vk = that.vk;
		that.options = options;
		that.init(options);
		// console.log(vk.getVuex('$user.userInfo'));
	},
	onUnload() {
		// 返回false阻止页面被销毁
		return false;
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() { },
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() { },
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() { },
	// 函数
	methods: {
		mychange(val, formData, column, index, option) {
			// console.log(formData)
			// console.log(option)
		},
		// 页面数据初始化函数
		async init(options) {
			originalForms["form1"] = JSON.parse(JSON.stringify(that.form1))
			originalForms["aquatic_form"] = JSON.parse(JSON.stringify(that.aquatic_form))
			this.queryForm1.formData = options;
			let delivery_company = undefined, btns = [];
			if (!this.$hasRole('admin')) {
				delivery_company = vk.getVuex('$user.userInfo').delivery_company;
				if (this.$hasPermission("detection-form-edit")) {
					btns.push('update')
				}
				if (this.$hasPermission("detection-form-del")) {
					btns.push('delete')
				}
			} else {
				btns = ['update', 'delete']
			}
			that.table1.btn = btns;


			vk.callFunction({
				url: `admin/base/client/sys/getalllist`,
				need_user_info: false,
				data: {
					page: 1,
					pageSize: 9999
				},
				success: (data) => {
					this.clients = data.rows;
					// if (this.$hasRole('admin') || this.$hasRole('ROLE_ZZ'))
					// 	this.clients = data.rows;
					// else {
					// 	this.clients = data.rows.filter(x => includes(delivery_company, x._id))

					// }
				}
			});
			vk.callFunction({
				url: 'admin/base/detection_category/sys/getList',
				data: {
					page: 1,
					pageSize: -1
				},
				success: (data) => {
					this.detection_categorys = data.rows;

				}
			});

			await vk.callFunction({
				url: 'admin/base/goods/sys/getList',
				data: {
					pageIndex: 1,
					pageSize: 999
				},
				success: (data) => {
					this.goods = concat(this.goods, data.rows);

				}
			});
			await vk.callFunction({
				url: 'admin/base/goods/sys/getList',
				data: {
					pageIndex: 2,
					pageSize: 999
				},
				success: (data) => {
					this.goods = concat(this.goods, data.rows);

				}
			});
			await vk.callFunction({
				url: 'admin/base/goods/sys/getList',
				data: {
					pageIndex: 3,
					pageSize: 999
				},
				success: (data) => {
					this.goods = concat(this.goods, data.rows);

				}
			});

		},
		clients_fomattr(val, row, column, index) {
			// console.log(this.categories.find(x=>x._id==val))
			return this.clients.find(x => x._id == val).name;

		},
		detection_categorys_fomattr(val, row, column, index) {
			// console.log(this.categories.find(x=>x._id==val))
			return this.detection_categorys.find(x => x._id == val).name;

		},
		samplelist_fomattr(val, row, column, index) {
			if (vk.pubfn.isNotNull(val)) {
				return val.length;
			} else
				return 0
		},
		// 页面跳转
		pageTo(path) {
			vk.navigateTo(path);
		},
		// 表单重置
		resetForm() {
			vk.pubfn.resetForm(originalForms, that);
		},
		// 搜索
		search() {
			that.$refs.table1.search();
		},
		// 刷新
		refresh() {
			that.$refs.table1.refresh();
		},
		// 获取当前选中的行的数据
		getCurrentRow() {
			return that.$refs.table1.getCurrentRow();
		},
		// 监听 - 行的选中高亮事件
		currentChange(val) {
			that.table1.selectItem = val;
		},
		// 当选择项发生变化时会触发该事件
		selectionChange(list) {
			that.table1.multipleSelection = list;
		},
		// 显示添加页面
		// 显示添加页面
		addBtn(type) {
			that.resetForm();
			if (that.$refs.xTable != undefined) {
				that.$refs.xTable.reloadData([]);
			}
			if (that.$refs.xAQTable != undefined) {
				that.$refs.xAQTable.reloadData([]);
			}
			if (that.$refs.xEnzymeTable != undefined) {
				that.$refs.xEnzymeTable.reloadData([]);
			}

			that.form1.props.action = 'admin/testing/detection-form/sys/add';
			that.aquatic_form.props.action = 'admin/testing/detection-form/sys/add';


			that.form1.props.formType = 'add';
			that.aquatic_form.props.formType = 'add';


			that.form1.props.title = '添加';
			that.aquatic_form.props.title = '添加(水产)';


			if (type == 'aquatic') {
				that.$set(that.aquatic_form.props, 'show', true);
			} else if (type == 'enzyme') {
				that.$set(that.enzyme_form.props, 'show', true);
			} else {
				that.form1.props.show = true;
			}

			that.$set(that.form1.data, 'type', type);
			that.$set(that.aquatic_form.data, 'type', type);

		},
		// 显示修改页面
		updateBtn({ item }) {
			that.form1.props.action = 'admin/testing/detection-form/sys/update';
			that.aquatic_form.props.action = 'admin/testing/detection-form/sys/update';


			that.form1.props.formType = 'update';
			that.aquatic_form.props.formType = 'update';


			that.form1.props.title = '编辑';
			that.aquatic_form.props.title = '编辑(水产)';


			if (that.$fn.isNotNull(item.type) && item.type == 'aquatic') {
				that.aquatic_form.data = item;
				vk.callFunction({
					url: 'admin/base/goods/sys/getsingel',
					data: {
						_id: item.sample_id
					},
					success: data => {
						let _arry = that.detection_categorys.filter(x => data.data.detection_category.includes(x._id));
						that.$set(that.aquatic_form.data, 'detection_category_list', _arry);
					}
				});
				that.aquatic_form.props.show = true;
			} else if (that.$fn.isNotNull(item.type) && item.type == 'enzyme') {
				that.enzyme_form.data = item;
				that.enzyme_form.props.show = true;
			} else {
				that.form1.props.show = true;
				that.form1.data = item;
			}
		},
		// 删除按钮
		deleteBtn({ item, deleteFn }) {
			deleteFn({
				action: "admin/testing/detection-form/sys/delete",
				data: {
					_id: item._id
				},
			});
		},
		// 监听 - 批量操作的按钮点击事件
		batchBtn(index) {
			switch (index) {
				case 1: this.mutifiPrint(); break;
				case 1: this.mutifiDel(); break;
				default: break;
			}
		},

		mutifiPrint() {

			that.print.printData = []
			that.print.show = true;

			let _printdt = that.table1.multipleSelection.filter(x => that.isDateBeforeOrEqualToToday(x.detect_time))
			that.print.printData = vk.pubfn.deepClone(_printdt)
		},
		mutifiDel() {
			let _delids = that.table1.multipleSelection.map(x => x._id);
			vk.callFunction({
				url: 'admin/testing/detection-form/sys/batchdel',
				title: '请求中...',
				data: {
					ids: _delids
				},
				success: (data) => {

				}
			});
		},
		activeCellMethod({ row, rowIndex }) {

			if (row.isSave != undefined && row.isSave == 1)
				return false;
			else
				return true;
		},
		getshowrows() {
			const $table = this.$refs.xTable
			let _rows = [];
			const { insertRecords, } = $table.getRecordset()
			if (this.$fn.isNull(this.form1.data.sample_list)) {
				this.form1.data.sample_list = []
			}

			if (this.form1.data.sample_list.length > 0)
				_rows = concat(this.form1.data.sample_list, insertRecords);
			else
				_rows = insertRecords;
			let _orderrows = orderBy(_rows, '_X_ROW_KEY', 'asc')
			return _orderrows;
		},
		async insertEvent(row) {
			const $table = this.$refs.xTable
			// if (this.getshowrows().length >= 47) {
			// 	vk.alert(`样品数量不能大于47个,请删除或者重新新建报告!`)
			// 	return;
			// }
			let _bh = pinyin.getCamelChars(this.form1.data.detection_standard_name)

			// 获取当前表格中未删除的样品数量，用于生成序号
			let currentSamples = this.form1.data.sample_list ? this.form1.data.sample_list.filter(x => !x.isdel) : [];
			let nextNumber = currentSamples.length + 1;
			_bh = _bh + this.padToThreeDigits(nextNumber);

			const record = {
				sampleno: _bh,
				detection_category: this.form1.data.detection_standard_name,
				rowNo: vk.pubfn.createOrderNo("ROW", 25),
				result: `经检测${this.form1.data.detection_standard_name}未超出相关要求`,
				result_value: 1,
				yxresult: '阴性',
				samplename: '',

			}
			const { row: newRow } = await $table.insertAt(record, row)
			$table.scrollToRow(newRow);
			await $table.setCurrentRow(newRow);
			await $table.setActiveCell(newRow, 'sampleno')
			this.$nextTick(async () => {
				let e = document.getElementById(`input_${newRow.rowNo}`).querySelector('.vxe-input--inner');;
				//console.log(e)
				if (e) {

					e.focus();
					if (e.select != undefined)
						e.select();
					e.click();
				}
			});
			let _data = $table.getTableData();
			if (this.$fn.isNotNull(_data.fullData) && _data.fullData.length > 0) {
				that.form1.props.columns.forEach(element => {
					console.log(element)
					if (element.key == "detection_category" || element.key == "detection_standard")
						that.$set(element, 'disabled', true)
				});
			}
		},
		async removeEvent(row) {

			//console.log(row)
			const $table = this.$refs.xTable
			// remove(this.form1.data.sample_list, x => x.rowNo == row.rowNo);
			// $table.loadData(this.form1.data.sample_list)

			$table.remove(row)

			let _data = $table.getTableData();
			if (this.$fn.isNull(_data.fullData) || _data.fullData.length < 1) {
				that.form1.props.columns.forEach(element => {
					// console.log(element)
					if (element.key != 'detection_user')
						that.$set(element, 'disabled', false)
				});
			}


		},

		getCurrentDate() {
			const today = new Date();
			const year = today.getFullYear();
			const month = (today.getMonth() + 1).toString().padStart(2, '0');
			const day = today.getDate().toString().padStart(2, '0');
			return `${year}${month}${day}`;
		},
		marksur(row) {
			if (this.$fn.isNull(row.sampleno)) {
				vk.alert(`样品编号不能为空`)
				return
			}


			if (this.$fn.isNull(row.samplename)) {
				vk.alert(`样品名称不能为空`)
				return
			}
			if (this.$fn.isNull(row.result)) {
				vk.alert(`检测结论不能为空`)
				return
			}
			that.$set(row, 'isSave', 1)
		},
		mark_aquatic_sur(row) {
			if (this.$fn.isNull(row.detection_category)) {
				vk.alert(`检测项目不能为空`);
				return;
			}
			if (this.$fn.isNull(row.result)) {
				vk.alert(`检测结论不能为空`);
				return;
			}
			that.$set(row, 'isSave', 1);
		},
		isDateBeforeOrEqualToToday(givenDate) {
			// 创建一个表示给定日期的Date对象
			const dateToCheck = new Date(givenDate);
			dateToCheck.setHours(0, 0, 0, 0);

			// 创建一个表示今天的Date对象
			const today = new Date();

			// 将今天的日期设置为当天的开始（即00:00:00）
			today.setHours(0, 0, 0, 0);

			// 比较两个日期的时间戳
			return dateToCheck <= today;
		},
		importBtn() {

		},
		handleFileChange(ss) {

			// 获取选择的文件对象
			const file = ss.raw
			// 创建 FileReader 对象
			const reader = new FileReader()
			let that = this;
			// 定义读取文件完成后的回调函数
			reader.onload = async (e) => {



				// 获取文件的二进制数据
				const data = e.target.result
				// 解析文件数据，获取工作簿对象
				const workbook = XLSX.read(data, { type: 'binary' })
				// 获取工作簿中的第一个工作表名称
				const sheetName = workbook.SheetNames[0]
				// 获取工作簿中的第一个工作表对象
				const sheet = workbook.Sheets[sheetName]
				// 将工作表对象转换为 JSON 格式的数据
				const jsonData = XLSX.utils.sheet_to_json(sheet, { range: 1, header: 'A' })
				// 定义一个空数组，用于存储读取的列的值
				const columnData = []
				const columnHeader = {};
				try {
					let tenancy = new Date().getTime()
					// 遍历 JSON 数据
					let _rowindex = 1;
					// if (jsonData.length > 47) {
					// 	throw new Error(`样品数超出最大限制,请检查上传的文件!`)
					// }
					jsonData.forEach((row, index) => {
						let _dd = row['A']
						let _client_name = row['B'].trim();
						let _goods_name = row['C'].trim();
						let det_category_name = row['E'].trim();
						let _client = find(this.clients, x => x.name == _client_name);
						let _goods = find(this.goods, x => x.name == _goods_name);
						let _det_cate = find(this.detection_categorys, x => x.name == det_category_name);
						if (this.$fn.isNull(_client)) {
							throw new Error(`第${_rowindex}行系统不存在${_client_name}这个委托单位/人,请检查!`)
						}
						if (this.$fn.isNull(_goods)) {
							throw new Error(`第${_rowindex}行系统不存在${_goods_name}这个样品名称,请检查!`)
						}
						if (this.$fn.isNull(_det_cate)) {
							throw new Error(`第${_rowindex}行系统不存在${det_category_name}这个检测项目,请检查!`)
						}
						if (!this.$hasRole('admin') && !this.$hasRole('ROLE_ZZ')) {


							if (this.$fn.isNull(vk.getVuex('$user.userInfo').delivery_company)) {
								throw new Error(`你没有导入任何配送公司权限,请联系管理员分配`)
							}
							if (!includes(vk.getVuex('$user.userInfo').delivery_company, _client._id)) {
								throw new Error(`当前用户没有导入${_client_name}权限,请联系管理员分配`)
							}
						}

						let addobj = find(columnData, x => x._dd == _dd);

						if (this.$fn.isNull(addobj)) {

							addobj = {}
							this.$set(addobj, '_dd', _dd)
							this.$set(addobj, 'sample_list', [])
							this.$set(addobj, 'detection_type', row['D'])
							this.$set(addobj, 'detection_category', _det_cate._id)
							this.$set(addobj, 'detection_standard_name', _det_cate.name)
							this.$set(addobj, 'detection_standard', _det_cate.standard)
							this.$set(addobj, 'client', _client._id)
							this.$set(addobj, 'client_name', _client_name)
							this.$set(addobj, 'detection_user', row['G'])
							this.$set(addobj, 'submitUser', row['F'])
							this.$set(addobj, 'detect_time', new Date().getTime())

							let _sample = {

							}
							let _bh = pinyin.getCamelChars(addobj.detection_standard_name) + '001'
							this.$set(_sample, 'sampleno', _bh)
							this.$set(_sample, 'samplename', _goods_name)
							this.$set(_sample, 'sample_id', _goods._id)
							this.$set(_sample, 'detection_category', _det_cate.name)
							this.$set(_sample, 'result', `经检测${addobj.detection_standard_name}未超出相关要求`)
							this.$set(_sample, 'yxresult', '阴性')
							this.$set(_sample, 'remark', row['H'])
							this.$set(_sample, 'isSave', 1)
							addobj.sample_list.push(_sample)
							columnData.push(addobj)
						} else {
							let _sample = {

							}
							let _bh = pinyin.getCamelChars(addobj.detection_standard_name) + this.padToThreeDigits(addobj.sample_list.length + 1);
							this.$set(_sample, 'sampleno', _bh)
							this.$set(_sample, 'samplename', _goods_name)
							this.$set(_sample, 'sample_id', _goods._id)
							this.$set(_sample, 'detection_category', _det_cate.name)

							this.$set(_sample, 'result', `经检测${addobj.detection_standard_name}未超出相关要求`)
							this.$set(_sample, 'yxresult', '阴性')
							this.$set(_sample, 'remark', row['H'])
							this.$set(_sample, 'isSave', 1)
							addobj.sample_list.push(_sample)
						}


						_rowindex++;
					})



				} catch (error) {
					vk.alert(error.message)
					return;
				}

				vk.callFunction({
					url: 'admin/testing/detection-form/sys/batchadd',
					title: '请求中...',
					data: {
						batch_datas: columnData
					},
					success: (data) => {
						vk.alert(`导入成功`)

						this.$refs.table1.refresh();
					}
				});

			}
			this.fileList = [];
			// 读取文件内容
			reader.readAsBinaryString(file)
		},
		padToThreeDigits(num) {
			// 将输入的数字转换为字符串
			const strNum = num.toString();

			// 使用padStart方法在字符串前面填充零，直到长度为3
			return strNum.padStart(3, '0');
		},
		async insertAquaticEvent(row) {
			const $table = this.$refs.xAQTable;

			const record = {
				detection_category: '',
				rowNo: vk.pubfn.createOrderNo('ROW', 25),
				result: `阴性`,
				result_value: 1,
				yxresult: '阴性',
				samplename: '',
				standardRequir: '不得检出'
			};

			let _data = $table.getTableData();
			if (this.$fn.isNotNull(_data.fullData)) {
				this.$set(record, `orderno`, _data.fullData.length + 1);
			} else {
				this.$set(record, `orderno`, 1);
			}

			const { row: newRow } = await $table.insertAt(record, row);

			this.$nextTick(async () => {
				$table.scrollToRow(newRow);
				await $table.setCurrentRow(newRow);
				await $table.setEditCell(newRow, 'detection_category');
				if (this.$fn.isNotNull(document.getElementById(`input_${newRow.rowNo}`))) {
					let e = document.getElementById(`input_${newRow.rowNo}`).querySelector('.vxe-input--inner');

					if (e) {
						e.focus();
						if (e.select != undefined) e.select();
						e.click();
					}
				}
			});
		},
		async removeAquaticEvent(row) {
			const $table = this.$refs.xAQTable;
			$table.remove(row);
		},
		handel_AQ_detection_categoryChange(val, form, row) {
			row.detection_standard = form.standard;
			row.detection_category = form.name;
			row.detection_include = form.detection_include;
			row.standardRequir = form.standardRequir;
			// 从商品信息带出单位
			if (that.$fn.isNotNull(that.aquatic_form.data.sample_id)) {
				const goods = that.goods.find(x => x._id === that.aquatic_form.data.sample_id);
				if (goods && goods.unit) {
					row.unit = goods.unit;
				} else {
					row.unit = 'μg/kg'; // 默认单位
				}
			} else {
				row.unit = 'μg/kg'; // 默认单位
			}
		},

		// 批量设置水产表单检测项目时使用（水产表单本身不修改样品编号，所以可以直接使用原方法）
		batchSetAquaticDetectionChange(val, form, row) {
			this.handel_AQ_detection_categoryChange(val, form, row);
		},
	},

	// 过滤器
	filters: {

	},

};
</script>

<style lang="scss" scoped>
.page-body {}

::deep.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type--week,
.vxe-input--panel.type--year {
	z-index: 9998 !important;
}

::deep.vxe-select--panel {
	z-index: 9997 !important;
}
</style>
